const express = require('express')
const router = express.Router()
const fs = require('fs')
const path = require('path');

const multer = require("multer");
const upload = multer({ dest: "./public/uploads/" })
const { queryDatabase } = require('../utils/common')
const { verifyToken } = require('../utils/token')

router.get('/swiper', async (req, res) => {
    let token = req.headers.authorization
    let verifyRes = verifyToken(token)
    if (verifyRes === 'err') {
        res.send({ msg: '身份认证已失效，请重新登录', code: 205 })
    } else {
        let sql = `select value from config where id=1`
        let result = await queryDatabase(sql)
        console.log(result)
        res.send({ msg: '获取成功', data: result[0].value, code: 200 })
    }
})
router.get('/filedata', async (req, res) => {
    let account = req.query.account
    let token = req.headers.authorization
    let verifyRes = verifyToken(token)
    if (verifyRes === 'err') {
        res.send({ msg: '身份认证已失效，请重新登录', code: 205 })
    } else {
        let sql = `select * from allfileslist WHERE account ='${account}' and status in('normal','share')`
        let fileData = await queryDatabase(sql)
        fileData.map((v) => {
            v.key = v.id
        })
        res.send({ msg: '获取成功', data: fileData, code: 200 })
    }
})
router.post('/avatar', upload.single("avatar"), (req, res) => {
    let avatar = req.file
    let { account } = req.body
    fs.readFile(avatar.path, (err, data) => {
        if (err) {
            console.log('fs.readFile()' + err)
            res.send({ code: 204, msg: "头像上传失败" })
            return false
        }
        let avatarName = avatar.originalname; // 获取图片名称
        let suffix = avatarName.substring(avatarName.lastIndexOf("."), avatarName.length) // 获取图片后缀名
        let newName = account + suffix // 拼接带后缀的完整图片名称
        let avatarUrl = path.join(__dirname, '../public/avatar/' + newName)
        fs.writeFile(avatarUrl, data, async (err) => {
            if (err) {
                console.log('fs.writeFile()' + err)
                res.send({ code: 204, msg: "头像上传失败" })
                return false
            }
            fs.unlink(path.join(__dirname, '../' + avatar.path), function (error) {
                if (error) {
                    console.log('fs.unlink' + error);
                    return false;
                }
            })
            let avatarPath = '/public/avatar/' + newName
            let updateSQL = `UPDATE usersinfo SET avatarurl='${avatarPath.replace(/\\/g, '/')}' WHERE account='${account}'`
            let result = await queryDatabase(updateSQL)
            if (result.affectedRows === 1) {
                res.send({ code: 200, msg: "头像上传成功", url: avatarPath })
            }

        })
    })
})
router.get('/folder', async (req, res) => {
    let { account, name } = req.query
    let token = req.headers.authorization
    let verifyRes = verifyToken(token)
    if (verifyRes === 'err') {
        res.send({ msg: '身份认证已失效，请重新登录', code: 205 })
    } else {
        let sql = `select id from ${account} WHERE name = '${name}'`
        let result = await queryDatabase(sql)
        let parent_id = result[0].id
        let sql1 = `select * from ${account} WHERE level='1.2' and parent_id=${parent_id}`
        let result1 = await queryDatabase(sql1)
        console.log(result1)
        res.send({ msg: '获取成功', data: result1, code: 200 })
    }
})
//删除文件
router.get('/delete', async (req, res) => {
    let { account, selectedFileId } = req.query
    let token = req.headers.authorization
    let verifyRes = verifyToken(token)
    if (verifyRes === 'err') {
        res.send({ msg: '身份认证已失效，请重新登录', code: 205 })
    } else {
        let uplateSQL = `UPDATE allfileslist SET status="recycle" WHERE account = '${account}' and id in(${selectedFileId.join(",")}) `
        let result = await queryDatabase(uplateSQL)
        if (result.affectedRows > 0) {
            let selectSQL = `select * from allfileslist WHERE account ='${account}' and status in('normal','share')`
            let fileData = await queryDatabase(selectSQL)
            fileData.map((v) => {
                v.key = v.id
            })
            res.send({ msg: '删除成功', data: fileData, code: 200 })
        }
    }
})
//重命名文件
router.get('/rename', async (req, res) => {
    let token = req.headers.authorization
    let verifyRes = verifyToken(token)
    if (verifyRes === 'err') {
        res.send({ msg: '身份认证已失效，请重新登录', code: 205 })
    } else {
        let { account, id, newName } = req.query
        console.log(account, id, newName)
        let sql = `select fileurl,suffix from allfileslist WHERE account ='${account}'and id='${id}'`
        let oldFileUrl = await queryDatabase(sql)
        let newFileUrl = '/public/userRoot/' + account + '/' + newName + oldFileUrl[0].suffix
        fs.rename(path.join(__dirname, '..' + oldFileUrl[0].fileurl), path.join(__dirname, '..' + newFileUrl), async (err) => {
            if (err) {
                throw err;
            }
            let sql = `UPDATE allfileslist SET name="${newName}",fileurl="${newFileUrl}" WHERE id = ${id} and account ='${account}'`
            let result = await queryDatabase(sql)
            if (result.affectedRows > 0) {
                let sql = `select * from allfileslist WHERE account ='${account}' and status in('normal','share') `
                let fileData = await queryDatabase(sql)
                fileData.map((v) => {
                    v.key = v.id
                })
                res.send({ msg: '重命名成功', data: fileData, code: 200 })
            }
        })


    }
})
//分享文件
router.get('/share', async (req, res) => {
    let { account, selectedFileId } = req.query
    let token = req.headers.authorization
    let verifyRes = verifyToken(token)
    if (verifyRes === 'err') {
        res.send({ msg: '身份认证已失效，请重新登录', code: 205 })
    } else {
        let updateSQL = `UPDATE allfileslist SET status="share" WHERE account = '${account}' and id in(${selectedFileId.join(",")}) `
        let result = await queryDatabase(updateSQL)
        console.log(result.affectedRows)
        if (result.affectedRows > 0) {
            let selectSQL = `SELECT * from allfileslist WHERE account ='${account}' and status in('normal','share') `
            let fileData = await queryDatabase(selectSQL)
            fileData.map((v) => {
                v.key = v.id
            })
            res.send({ msg: '分享成功', data: fileData, code: 200 })
        }
    }
})

module.exports = router